const {
    Keypair,
    Transaction,
    SystemProgram,
    LAMPORTS_PER_SOL,
    TransactionMessage,
    TransactionInstruction
} = require("@solana/web3.js");
const config = require('./config');

const SolChain = require('./SolChain');
const {transactionMessage }= require('./utils');

const {
    getKeyPairUser1, getKeyPairUser2, getKeyPairFromSeed
} = require('./MyKeypair');

const { sha256 } =require("@cosmjs/crypto");
const { toHex } =require("@cosmjs/encoding");
const run = async ()=> {
    let solChain = new SolChain(config.localNode);
    let hello_program_keypar = require('../simple-hello_world/target/deploy/simple_hello_world-keypair.json');
    let secretKey = Uint8Array.from(hello_program_keypar);
    let programKeypair = Keypair.fromSecretKey(secretKey);

    let programID = programKeypair.publicKey;
    console.log('programID: ', programID);

    const fromKeypair = await getKeyPairFromSeed();

    console.log('fromKeypair.publicKey: ', fromKeypair.publicKey.toBase58())

    let instruction = new TransactionInstruction({

        keys:[{pubkey:fromKeypair.publicKey, isSigner:false, isWritable:true}],
        programId:programID,
        data:Buffer.from("{index:6}")

    });

    let latestBlockhash = await solChain.getLatestBlockhash();

    let payerPk = fromKeypair.publicKey;

    let tx = transactionMessage(payerPk, latestBlockhash.blockhash, [instruction]);
    console.log('tx: ', tx);


    let balance = await solChain.getBalance(fromKeypair.publicKey);
    console.log('from balance: ', balance);
    await tx.sign([fromKeypair]);
    let rawTx = tx.serialize();


    let ret = await solChain.sendRawTransaction(rawTx);
    console.log('ret: ', ret);
}

run();